import React, { useEffect, useState } from 'react';
import { useHistory } from "react-router-dom";
import './doctorWorkstation.less';
import http from "../../model/http";
import { dateFormat } from "../../model/code";
import { Accordion, Flex, List, Card, Menu, NavBar, ActivityIndicator,PullToRefresh } from 'antd-mobile'
import Header from "../../components/header/Header";
import { Calendar } from 'react-h5-calendar';  

function DoctorWorkstation() {
    const history = useHistory();
    const [show, setShow] = useState(false)
    const [initData, setInitData] = useState([]) // 菜单数据
    const [initDataValue,setInitDataValue] = useState([])  // 默认value 
    const [expertName, setExperName] = useState([]) // 部门名称
    
    const [idString, setIdString] = useState('') // 选中的医生的id 字符串拼接起来

    const [styleWidth, setStyleWidth] = useState('')

    const nowTimeStamp = new Date(); 
    const [dateValue, setDateValue] = useState(nowTimeStamp) // 选择时间

    const [jurisdiction, setJurisdiction] = useState('') // 用户的权限
    
    const [doctorList, setDoctorList] = useState([]) // 医生的信息
    // const [load,setLoad] = useState(false);
 
    useEffect(async () => {
        let qx = sessionStorage.getItem('doctorJurisdiction') ? JSON.parse(sessionStorage.getItem('doctorJurisdiction')): ''
        setJurisdiction(qx)

        if(qx != '' && qx.authority == '3'){
            // http://wxwork.gzsg.cn/wxwork/scheduler/getAllExpertTrTime
            const result = await http.post('/scheduler/getAllExpertTrTime',{
                sch_date: dateFormat(dateValue, 'yyyy-MM-dd'),
                deptId: qx.dept_group_id,
                expertIds: qx.erp_id
            }) 
            setDoctorList(result.data)  
            // 设置默认的部门名称
            setExperName([qx.deptname,qx.dept_group_id])
            
            setIdString(qx.erp_id) 
        }else{
            // 查询部门列表数据
            const result = await http.get('/expert/list')
            setInitData(result.data)
            // 设置默认选中的菜单
            setInitDataValue([result.data[0].value, []])
            // 设置默认的部门名称
            setExperName([result.data[0].label,result.data[0].value])
        
            
            // http://wxwork.gzsg.cn/wxwork/manager/getDeptPersonList?hosId=1&userId=xx&managerId=1629697426248&deptId=DE0011&userType=3
            // const expertList = await http.post('/manager/getDeptPersonList',{
            //     userType: 3,
            //     deptId: 'DE0011'
            // })

            const expertList = await http.post('/scheduler/getAllExpertTrTime',{
                sch_date: dateFormat(dateValue, 'yyyy-MM-dd'),
                deptId: result.data[0].value,
            })
            setDoctorList(expertList.data) 
        }


        console.log('执行') 
        setStyleWidth(document.getElementById('rightBox').scrollWidth)
    }, [])


    const navChange = (value) => {
        console.log("1:",value)
    }
    // 菜单里面点击确定
    const onOk = (value) => {
        console.log(value); 
        
        // 获取到label
        let label = '';
        initData.forEach((dataItem) => {
            if (dataItem.value === value[0]) {
                label = dataItem.label;
                if (dataItem.children && value[1]) {
                    dataItem.children.forEach((cItem) => {
                        if (cItem.value === value[1]) {
                            label += ` ${cItem.label}`;
                        }
                    });
                }
            }
        });
        setExperName([label, value[0]])

        
        console.log(label);


        let string = ''
        let arrStr = []
        console.log(value[1])
        if(value[1].length > 0){
            value[1].map(item => { 
                string += item.match(/(\S*)-/)[1] + ','
                arrStr.push(item)
            })
        }
        
        
        setIdString(string) 
        // 点击确定的时候调请求
        doctorListFunc(dateFormat(dateValue, 'yyyy-MM-dd'), value[0], string)

        // 点击确定的时候默认选中
        setInitDataValue([value[0], arrStr])

        onMaskClick(); 
    }
    // 点击菜单里面的重置
    const handleRemove = () => {
        doctorListFunc(dateFormat(dateValue, 'yyyy-MM-dd'), expertName[1], '')
        // 点击重置的时候去除选中
        setInitDataValue([expertName[1], []])
        setIdString('')
    }

    const onMaskClick = () => {
        setShow(false)
        document.body.removeEventListener('touchmove', window.scroll,{passive: true});
        document.body.style.overflow = 'auto';
    }

    // 点击菜单显示
    const handleClick = (e) => {
        e.preventDefault();  
        setShow(!show)
        
        if(!show){
            document.body.addEventListener("touchmove", window.scroll, {passive: false });
            document.body.style.overflow = 'hidden';
        }
    }

    // menu 菜单的展开内容
    const menuEl = (
        <Menu
            className="multi-foo-menu"
            data={initData}
            value={initDataValue}
            onChange={(value) => navChange(value)}
            onOk={(value) => onOk(value)}
            onCancel={() => onMaskClick()}
            height={500}
            multiSelect
        />
    );
    const loadingEl = (
        <div style={{ width: '100%', height: 500, display: 'flex', justifyContent: 'center' }}>
            <ActivityIndicator size="large" />
        </div>
    );
    

    const doctorListFunc = async (d, tid, idStr) => {
        const expertList = await http.post('/scheduler/getAllExpertTrTime',{
            sch_date: d,
            deptId: tid,
            expertIds: idStr
        })
        setDoctorList(expertList.data) 
        // 重新计算宽度
        setTimeout(() => {
            setStyleWidth(document.getElementById('rightBox').scrollWidth)     
        }, 50);
    }

    

    // 点击日期
    const onDateClick = (d) => {
        setDateValue(d.$d)   
        console.log(dateFormat(d.$d, 'yyyy-MM-dd'))
        
        // console.log(expertName[1].match(/(\S*)-/)[1])
        
        // 调用请求
        doctorListFunc(dateFormat(d.$d, 'yyyy-MM-dd'), expertName[1], idString) 
    }
    // 点击手术
    const operationClick = (elemt) => {
        console.log(elemt)
        history.push(`/doctorWorkstation/list`, {
            operationInfo: elemt
        })
    }

    return (
        <div className="v-doctor-work-station">
            <div className={show ? 'menu-active' : ''}>
                <div>
                    <NavBar
                        // leftContent="Menu"
                        mode="light" 
                        icon={jurisdiction.authority != '3' && (<img src="https://gw.alipayobjects.com/zos/rmsportal/iXVHARNNlmdCGnwWxQPH.svg" className="am-icon am-icon-md" alt="" />)}
                        onLeftClick={(e) => {jurisdiction.authority != '3' && (handleClick(e))}}
                        className="top-nav-bar"
                        rightContent={jurisdiction.authority != '3' && (<div onClick={() => handleRemove()}>重置</div>)}
                        
                    >
                        {expertName[0]}
                    </NavBar>
                </div>
                {show ? initData ? menuEl : loadingEl : null}
                {show ? <div className="menu-mask" onClick={() => onMaskClick()} /> : null}
            </div>
            
            <div className="doctorWorkStation-content">
                <Calendar 
                    onDateClick={(d) => onDateClick(d)}
                    showType={'week'}
                    markDates={[]}
                    markType="dot"
                    currentDate={dateValue} 
                />

                {/* <PullToRefresh
                    style={{
                        height: '600px',
                        overflow: 'auto',
                    }}
                    indicator={true}
                    direction='down'
                    refreshing={load}
                    onRefresh={() => {
                        setLoad(true)
                    setTimeout(() => {
                        setLoad(false)
                    }, 1000);
                    }}
                > */}
                    <div className="content-left-box">
                        <ul>
                            {doctorList.map(item => (
                                <li>
                                    <span style={{"fontSize":"18px"}}>{item.expertname}</span> 
                                </li>
                            ))}  
                        </ul>
                    </div>
                    <div className="content-right-box" id="rightBox">
                        <ul style={{width: styleWidth}}>
                            {doctorList.map(item => ( 
                                <li> 
                                    <div className="scroll-box">
                                        {item.data.map(elem => (
                                            <div className={`card-box ${elem.confirm_state == '1'?'work-in':(elem.confirm_state == '2'?'work-in2':(elem.confirm_state == '3'?'work-in3':''))}`} onClick={() => operationClick(elem)}>
                                                <p>{elem.customer_name}[{elem.customer_card_no}] <b className="important-b-red" style={{color:'red',marginLeft:'auto'}}>{elem.is_today===1 && ('当日')}</b></p>
                                                <p><b>{elem.confirm_state_name} </b><b style={{margin:'0 10px'}}>{elem.estimate_time}分钟</b><b>{elem.consult_man_name}</b></p> 
                                                <p>{elem.begin_time} ~ {elem.end_time}</p>  
                                                
                                            </div> 
                                        ))} 
                                    </div> 
                                    <div className="clear"></div>
                                </li> 
                            ))} 
                            
                        </ul>
                    </div>
                    {doctorList.length < 1 && (<div style={{textAlign:'center',marginTop:'10px',color:'#bbb',fontSize:'14px'}}>暂无更多数据</div>)}
                {/* </PullToRefresh> */}
                

                <div className="clear"></div>
            </div>
            <Header />
        </div>

    );
}
export default DoctorWorkstation;

// 0 未开启
// 1 进行中
// 2 已完成